class Solution:
    def removeDuplicateLetters(self, text: str) -> str:
        re = []
        hash1 = [-1 for _ in range(26)]
        a = ord('a')
        for i in range(len(text)):
            c = ord(text[i]) - a
            hash1[c] = i
        inHash = set()
        i = 0
        while i < len(text):
            nowLetter = text[i]
            if nowLetter in inHash:
                i = i + 1
                continue
            if len(re) == 0:
                re.append(i)
                inHash.add(nowLetter)
                i = i + 1
                continue
            if text[re[-1]] > nowLetter and hash1[ord(text[re[-1]]) - a] > i:
                inHash.remove(text[re.pop(-1)])
                continue
            else:
                re.append(i)
                inHash.add(nowLetter)
                i = i + 1

        return "".join([text[i] for i in re])


if __name__ == '__main__':
    so = Solution()
    nums1 = "leettrcode"
    r = so.removeDuplicateLetters(nums1)
    print(r)
